﻿using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Wings.Web.Domain;
using Wings.Web.Repostory;

namespace Wings.Web.Repostory
{
    public class Repostory<T, Key> : IRepostory<T, Key> where T : class, IEntity<Key>, new()
    {
        protected readonly ISession _session;
        protected readonly ITransaction _transaction;
        public Repostory(ISession session)
        {
    _session = session;
            _transaction = _session.BeginTransaction();
        }

        public void Create(T t)
        {
             _session.Save(t);
        }

        public void Delete(Key id)
        {
            var model = Get(id);
            _session.Delete(model);
        }

        public T Get(Expression<Func<T, bool>> where)
        {
           return _session.QueryOver<T>().Where(where).List().FirstOrDefault();
        }

        public T Get(Key Id)
        {
             return _session.QueryOver<T>().Where(x => x.ID.Equals(Id)).List().FirstOrDefault();
        }

        public IList<T> GetAll()
        {
            throw new NotImplementedException();
        }

        public IList<T> Query(Expression<Func<T, bool>> where)
        {
            return _session.QueryOver<T>().Where(where).List();
        }

        public void Save(T t)
        {
            _session.SaveOrUpdate(t);
        }
        public void Comment()
        {
          
                _transaction.Commit();
                _session.Flush();
            _transaction.Dispose();
        }
        public void Update(T t)
        {
            _session.Update(t);
        }
    }
}
